<?php
/**
 * Created by JetBrains PhpStorm.
 * User: WEI JIAN XIANG
 * Date: 5/21/13
 * Time: 9:39 PM
 * To change this template use File | Settings | File Templates.
 */

class Core_Model_DbTable_Config extends Zend_Db_Table_Abstract{
    protected $_name = "config";
    public function getAll(){
        return $this->fetchAll();
    }

    public function getByKey($key){
        try{
            $res = $this->fetchRow($this->getAdapter()->quoteInto("`key` = (?)", $key));
            if(!is_null($res)){
                return $res->toArray();
            }
            return $res;
        }catch (Exception $ex){
            return null;
        }
    }

    public function insertConfig($key, $value){
        try{
            if(is_null($this->getByKey($key))){
                return $this->insert(array("key" => $key, "value" => $value));
            }else{
                $this->updateConfig($key, $value);
            }
        }catch (Exception $ex){
            return null;
        }
    }

    public function updateConfig($key, $value){
        try{
            return $this->update(array("value" => $value), $this->getAdapter()->quoteInto('`key` = (?)', $key));
        }catch (Exception $ex){
            return null;
        }
    }
    
    public function getMailSettings() {
        $email_keys = array (
            'smtp_host',
            'smtp_password',
            'smtp_port',
            'smtp_user'
        );
        $cond = $this->getAdapter()->quoteInto("`key` IN (?)", $email_keys);
        $select = $this->select()
                       ->from($this->_name)
                       ->where($cond);
        $db_result = $this->fetchAll($select);
        $result = array();
        foreach ($db_result as $config) {
            $result[$config->key] = $config->value;
        }
        return $result;
    }
}